/**
 * @fileOverview GIS地图控件访问接口
 * @author <a href='mailto:lifuwei1984@163.com'>lifuwei</a>
 */
abbp.provide('abbp.gis.supermap.Map');

/* 加载SuperMap类库 */
abbp.include(abbp.baseJsPath + 'lib/supermap/scripts/include.js');

/**
 * 地图构造函数
 * 
 * @param {object}
 *            y params 构造参数，类似div容器之类参数,有些初始化信息类在配置参数里面实现
 * @constructor
 */
abbp.gis.supermap.Map = function(params) {
	this.mapUrl = SuperMapConfig.MAP_URL;
	this.isMeasureDistance = true;
	this.mapBounds = new SuperMap.Web.Core.Rectangle2D(107.2448771539,
			33.5681529188, 110.1526020805, 35.0220153821);
	this.sgsMapResolutions = SuperMapConfig.SGS_MAP_RESOLUTIONS;
	
	this.sgsMapScales = SuperMapConfig.SGS_MAP_SCALES;
	this.map = $create(SuperMap.Web.Mapping.Map, {
				scales : this.sgsMapScales
			}, null, null, $get(params.mapContainer));

	this.loadBaseMap();

	// 初始化图层
	this.layer = $create(SuperMap.Web.Mapping.TiledDynamicRESTLayer, {
				url : this.mapUrl,
				transparent : true
			}, {
				initialized : this.restLayerInitialized_.bind(this)
			}, null, null);

	abbp.ajax.servlet.doGet(REST_SERVICES_ADDRESS + "gis/layers",
			function(req) {
				var json = JSON.parse(req.responseText);
				this.layersInfo = eval('(' + json['result']['value'] + ')');
			}.bind(this), null, null, {
				'accept' : 'application/json'
			});

	this.getTemplateLayer();

};

abbp.gis.supermap.Map.prototype.toString = function() {
	return 'ABBP-GIS-Map';
};

/**
 * extend属性
 * 
 * @type {abbp.gis.supermap.Extent}
 */
abbp.gis.supermap.Map.prototype.extend;
/**
 * 地图比例尺
 * 
 * @type {double}
 */
abbp.gis.supermap.Map.prototype.scale;

/**
 * 图层配置列表，为LayerConfig列表
 */
abbp.gis.supermap.Map.prototype.layersConfig = [];

/**
 * 加载西安共享平台底图
 */
abbp.gis.supermap.Map.prototype.loadBaseMap = function() {

	var layerRestsgs = new SuperMap.Web.Mapping.TiledDynamicRESTLayerExtend();
	var layerUrl = SuperMapConfig.SGS_MAP_URL;
	layerRestsgs.set_url(layerUrl);

	layerRestsgs.set_refResolution(this.sgsMapResolutions[9]);

	layerRestsgs.set_refScale(this.sgsMapScales[9]);
	layerRestsgs.set_bounds(this.mapBounds);
	layerRestsgs.initialize();

	this.map.set_scales(this.sgsMapScales);
	this.map.set_resolutions(this.sgsMapResolutions);

	this.map.addLayer(layerRestsgs);
};

/**
 * 加载共享平台影像数据
 */
abbp.gis.supermap.Map.prototype.loadImageMap = function() {
	this.map.removeLayer();
	this.map.set_scales(SuperMapConfig.SGS_IMG_SCALES);
	this.map.set_resolutions(SuperMapConfig.SGS_IMG_RESOLUTIONS);

	var layerRestsgs = new SuperMap.Web.Mapping.TiledDynamicRESTLayerExtend();
	var layerUrl = SuperMapConfig.SGS_IMG_URL;
	layerRestsgs.set_url(layerUrl);

	layerRestsgs.set_refResolution(this.sgsMapResolutions[0]);

	layerRestsgs.set_refScale(this.sgsMapScales[0]);
	layerRestsgs.set_bounds(this.mapBounds);
	layerRestsgs.initialize();

	this.map.addLayer(layerRestsgs);
	this.map.setLayers([this.featuresLayer, this.markerLayer]);
	if (GlobalContext.eqMgr && GlobalContext.eqMgr.EQInfo) {
			this.addEqCenterMark(GlobalContext.eqMgr.EQInfo);
		}
};

/**
 * Rest图层初始化完成处理方法
 * 
 * @param layer
 *            图层初始化完成后传回 Layer 对象
 */
abbp.gis.supermap.Map.prototype.restLayerInitialized_ = function(layer) {
	this.featuresLayer = SuperMap.Web.Mapping.FeaturesLayerFactory.make();
	this.markerLayer = $create(SuperMap.Web.Mapping.MarkerLayer, null, null,
			null, null);

	// 清除当前地图控件中的所有图层
	// this.map.removeLayer();

	// 在地图控件中加载图层
	this.map.setLayers([this.layer, this.featuresLayer, this.markerLayer]);

	this.getLayersConfig(this.getLayerConfigCompleted_);
	var i= layer.get_url().indexOf('StationLD');
	i+=layer.get_url().indexOf('EQ_tempLD');
	if (i<0) {
		if (GlobalContext.eqMgr && GlobalContext.eqMgr.EQInfo) {
			this.addEqCenterMark(GlobalContext.eqMgr.EQInfo);
		}
	}

	// 初始化鹰眼图层
	this.overViewMap_Layer = $create(
			SuperMap.Web.Mapping.TiledDynamicRESTLayer, {
				url : SuperMapConfig.OVERVIEW_MAP_URL
			}, {
				initialized : this.overViewMapLayerInitialized_.bind(this)
			}, null, null);

};

abbp.gis.supermap.Map.prototype.getLayerConfigCompleted_ = function(
		queryableLayers) {
	this.layersConfig = queryableLayers;
}

/**
 * 初始化鹰眼控件
 * 
 * @param overvierMap_layer
 *            鹰眼图层
 */
abbp.gis.supermap.Map.prototype.overViewMapLayerInitialized_ = function(
		overviewMap_layer) {

	var overviewMap = new SuperMap.Web.Controls.OverviewMap({
				'id' : 'overviewMap',
				'layer' : overviewMap_layer,
				'map' : this.map,
				'size' : {
					width : 100,
					height : 100
				}
			});
	var scaleBar = new SuperMap.Web.Controls.ScaleBar({
				'id' : 'scaleBar',
				'scaleBarStyle' : {
					'color' : 'black',
					'fontSize' : 2,
					'mode' : 1
				}
			});
			
	var zoomSlider = new SuperMap.Web.Controls.ZoomSlider({id:"zoomSlider",pos:new SuperMap.Web.Core.Point(43, 40)});

	var controls = [overviewMap,zoomSlider,scaleBar];
	this.map.addControls(controls);
};

abbp.gis.supermap.Map.prototype.onMouseMove = function(handler) {
	this.map.add_mouseMove(function(coordArgs) {
				var x = coordArgs.mapCoord.x.toFixed(2);
				var y = coordArgs.mapCoord.y.toFixed(2);
				handler(x, y);
			});
};

/**
 * 获取专题图模板图层
 */
abbp.gis.supermap.Map.prototype.getTemplateLayer = function() {
	var getLayersInfoService = new SuperMap.Web.iServerJava6R.GetLayersInfoService(SuperMapConfig.TEMPLATE_MAP_URL);
	getLayersInfoService.add_processCompleted(this.getTemplateLayerCompleted_
			.bind(this));
	getLayersInfoService.processAsync();
};

/**
 * 获取专题图模板图层回调
 * 
 * @param {}
 *            layersInfoEventArgs
 */
abbp.gis.supermap.Map.prototype.getTemplateLayerCompleted_ = function(
		layersInfoEventArgs) {
	this.templateSublayers = {};
	var result = layersInfoEventArgs.result;

	for (var i = 0, len1 = result.length; i < len1; i++) {
		var subLayers = result[i].subLayers;
		for (var j = 0, len2 = subLayers.length; j < len2; j++) {
			this.templateSublayers[subLayers[j].name] = subLayers[j];
		}
	}
};

/**
 * 获取可查询图层信息
 * 
 * @param callback
 *            回调函数，参数为可查询图层信息，类型为 abbp.gis.supermap.LayerConfig
 */
abbp.gis.supermap.Map.prototype.getLayersConfig = function(callback) {
	var getLayersInfoService = new SuperMap.Web.iServerJava6R.GetLayersInfoService(this.mapUrl);
	getLayersInfoService.add_processCompleted(function(getLayersInfoEventArgs) {
				this
						.getLayersConfigCompleted_(getLayersInfoEventArgs,
								callback)
			}.bind(this));
	getLayersInfoService.processAsync();
};

/**
 * 获取图层信息回调
 */
abbp.gis.supermap.Map.prototype.getLayersConfigCompleted_ = function(
		layersInfoEventArgs, callback) {
	var result = layersInfoEventArgs.result;
	this.queryConfig = new abbp.gis.supermap.QueryConfig();
	var queryableLayers = [];
	for (var i = 0, len1 = result.length; i < len1; i++) {
		var subLayers = result[i].subLayers;
		for (var j = 0, len2 = subLayers.length; j < len2; j++) {
			var subLayer = subLayers[j];
			var layerConfig = abbp.gis.supermap.LayerConfig
					.fromSupermapLayer(subLayer);
			if (subLayer.name == 'Dangerous_Source@orcl_xian') {
				this.dangerousLayer = subLayer;
			}
			if (layerConfig && subLayer.queryable) {
				queryableLayers.push(layerConfig)
				var queryLayerParmam = new abbp.gis.supermap.QueryLayerParam();
				queryLayerParmam.name = layerConfig.name;
				this.queryConfig.queryLayerParams.push(queryLayerParmam);
			}
		}
	}
	callback(queryableLayers);

};

/**
 * 获取图层字段值
 * 
 * @param layerName
 *            图层名
 * @param callback
 *            回调函数,参数为字段信息数组[{'caption':'字段标题','name':'字段名'}]
 */
abbp.gis.supermap.Map.prototype.getLayerFields = function(layerName, callback) {
	var getFieldsService = new SuperMap.Web.iServerJava6R.QueryBySQLService(this.mapUrl);
	var queryParamters = new SuperMap.Web.iServerJava6R.QueryBySQLParameters();
	var filterParameter = new SuperMap.Web.iServerJava6R.FilterParameter();
	queryParamters.expectCount = 1;
	queryParamters.queryOption = SuperMap.Web.iServerJava6R.QueryOption.ATTRIBUTE;
	filterParameter.name = layerName;
	queryParamters.queryParams = [filterParameter];

	getFieldsService.add_processCompleted(function(fieldsEventArgs) {
				this.getFieldsCompleted_(fieldsEventArgs, callback);
			}.bind(this))
	getFieldsService.processAsync(queryParamters);
};

/**
 * 获取字段信息回调方法
 */
abbp.gis.supermap.Map.prototype.getFieldsCompleted_ = function(fieldsEventArgs,
		callback) {
	var recordset = fieldsEventArgs.result.recordsets[0];
	var fieldNames = recordset.fields;
	var fields = [];
	var fieldCaptions = recordset.fieldCaptions;
	for (var i = 0, len = fieldNames.length; i < len; i++) {
		var filedName = fieldNames[i];
		if (filedName.toLowerCase().indexOf('sm', 0) < 0) {
			fields.push({
						'caption' : fieldCaptions[i],
						'name' : fieldNames[i]
					});
		}
	}
	callback(fields)

};

/**
 * 在一个图层上查询符合 SQL 条件的空间地物信息
 * 
 * @param layerName
 *            图层名
 * @param attributeFilter
 *            查询条件
 */
abbp.gis.supermap.Map.prototype.sqlQuery = function(layerName, field,
		condition, value) {
	if (value == '') {
		alert('请输入查询值');
		return;
	}
	var expresstion = '';
	switch (condition) {
		case 'equals' :
			expresstion = '=';
		case 'notEquals' :
			expresstion = '<>';
			break;
		case 'like' :
			expresstion = 'like';
			break;
		case 'smaller' :
			expresstion = '<';
			break;
		case 'bigger' :
			expresstion = '>';
			break;
		case 'notSmaller' :
			expresstion = '>='
			break;
		case 'notBigger' :
			expresstion = '<='
			break;
		case 'isNotNull' :
			expresstion = 'is not null';
			break;
		case 'isNull' :
			expresstion = 'is null'
			break;
	}
	if (expresstion == 'like') {
		attributeFilter = field + ' like \'%' + value + '%\'';
	} else {
		attributeFilter = field + ' ' + expresstion + ' \'' + value + '\''
	}

	var sqlQueryService = new SuperMap.Web.iServerJava6R.QueryBySQLService(this.mapUrl);
	var queryParamters = new SuperMap.Web.iServerJava6R.QueryBySQLParameters();
	var filterParameter = new SuperMap.Web.iServerJava6R.FilterParameter();
	filterParameter.name = layerName;
	filterParameter.attributeFilter = attributeFilter;
	queryParamters.queryParams = [filterParameter];

	sqlQueryService.add_processCompleted(function(queryEventArgs) {
				var recordsets = queryEventArgs.result.recordsets;
				this.queryResultDisplay(recordsets);
			}.bind(this));
	sqlQueryService.processAsync(queryParamters);
};

/**
 * 查询结果展示
 * 
 * @param recordsets
 *            查询结果数据集集合 类型为[abbp.gis.supermap.RecordSet]
 */
abbp.gis.supermap.Map.prototype.queryResultDisplay = function(smRecordsets) {
	var dataGrid = '<?xml version="1.0" encoding="UTF-8"?><datagrid version="1.0">';
	for (var i = 0, len1 = smRecordsets.length; i < len1; i++) {
		var smRecordset = smRecordsets[i];
		var recordset = abbp.gis.supermap.RecordSet
				.fromSuperMapRecordSet(smRecordset);
		var records = recordset.records;
		if (records.length > 0) {
			var layerInfo = abbp.gis.supermap.LayerConfig.LAYERS[recordset.layerName];
			if (layerInfo) {
				var caption = layerInfo['caption'];
				var fields = layerInfo['fields'];
				dataGrid = dataGrid + '<grid><params><caption>' + caption
						+ '查询结果' + '</caption>';
				dataGrid = dataGrid + '<locate>' + smRecordset.datasetName
						+ '</locate></params><columns>';
				var columns = '';
				var rows = '';
				for (var j = 0, len2 = fields.length; j < len2; j++) {
					columns = columns + '<column name="' + fields[j]['name']
							+ '_" caption="' + fields[j]['caption']
							+ '" visible="true"/>';
				}
				columns = columns
						+ '<column name="SMID" caption="图形编号" visible="false"/>'
				dataGrid = dataGrid + columns + '</columns><rows>';
				for (var k = 0, len3 = records.length; k < len3; k++) {
					rows = rows + '<row>';
					for (var l = 0, len4 = fields.length; l < len4; l++) {
						var filedName = fields[l]['name'];
						rows = rows + '<' + filedName + '_>'
								+ records[k].getValue(filedName) + '</'
								+ filedName + '_>';
					}
					rows = rows + '<SMID>' + records[k].getValue('SMID')
							+ '</SMID></row>';
				}
				dataGrid = dataGrid + rows + '</rows></grid>';
			}
		}
	}
	dataGrid = dataGrid + '</datagrid>';
	var win = new abbp.ui.DataGridWindow({
				title : '表格数据'
			});
	win.setWidth(800);
	win.setHeight(500);
	win.showXmlData(dataGrid);
	win.show();
};

/**
 * 创建矢量要素图层
 */
abbp.gis.supermap.Map.prototype.initFeaturesLayer_ = function() {
	var featuresLayer = SuperMap.Web.Mapping.FeaturesLayerFactory.make();
	return featuresLayer;
};

/**
 * 重新定位,如果参数为空，恢复到默认地图
 */
abbp.gis.supermap.Map.prototype.reload = function(mapName) {
	this.map.removeLayer();
	if (mapName) {
		this.mapUrl = BASE_MAP_URL + mapName;
	} else {// 加载默认地图
		this.mapUrl = SuperMapConfig.MAP_URL;
		this.loadBaseMap();
	}
	this.layer = $create(SuperMap.Web.Mapping.TiledDynamicRESTLayer, {
				url : this.mapUrl,
				transparent : true

			}, {
				initialized : this.restLayerInitialized_.bind(this)
			}, null, null);
};

/**
 * 加载地震专题图
 * 
 * @param {}
 *            id 地震事件编号
 * @param {}
 *            code 模型代码
 */
abbp.gis.supermap.Map.prototype.reloadTheme = function(id, code) {
	if (id && code) {
		var newCode = code.replace(/\./g, "_");
		this.mapUrl = BASE_MAP_URL + "EQ_" + id + "_" + newCode;

		this.layer = $create(SuperMap.Web.Mapping.TiledDynamicRESTLayer, {
					url : this.mapUrl
				}, {
					initialized : this.restLayerInitialized_.bind(this)
				}, null, null);
	}
};

/**
 * 刷新地图
 */
abbp.gis.supermap.Map.prototype.refreshMap = function() {
	this.map.refresh();
};

/**
 * 全图
 */
abbp.gis.supermap.Map.prototype.fullExtent = function() {
	this.map.viewEntire();
};

/**
 * 地图平移
 */
abbp.gis.supermap.Map.prototype.pan = function() {
	var panAction = $create(SuperMap.Web.Actions.Pan, {
				map : this.map
			}, null, null, null);
	this.map.set_action(panAction);
};

/**
 * 拉框放大地图
 */
abbp.gis.supermap.Map.prototype.zoomIn = function() {
	var zoomInAction = $create(SuperMap.Web.Actions.ZoomIn, {
				map : this.map
			}, null, null, null);
	this.map.set_action(zoomInAction);
};

/**
 * 拉框缩小地图
 */
abbp.gis.supermap.Map.prototype.zoomOut = function() {
	var zoomOutAction = $create(SuperMap.Web.Actions.ZoomOut, {
				map : this.map
			}, null, null, null);
	this.map.set_action(zoomOutAction);
};

/**
 * 前一视图（supermap未实现，预留接口）
 */
abbp.gis.supermap.Map.prototype.preView = function() {
};

/**
 * 后一视图（supermap未实现，预留接口）
 */
abbp.gis.supermap.Map.prototype.nextView = function() {
};

/**
 * @param {abbp.gis.supermap.QueryConfig}
 *            queryConfig 参数配置
 * @param {function}
 *            onComplete 回调
 */
abbp.gis.supermap.Map.prototype.geometryQuery = function(geo, queryLayerParams,
		callback) {
	// 构造查询参数
	var queryParams = [];
	// var queryLayerParams = this.queryConfig.queryLayerParams;
	var queryByGeometryParameters = new SuperMap.Web.iServerJava6R.QueryByGeometryParameters();
	for (var i = 0, len = queryLayerParams.length; i < len; i++) {
		var queryParam = new SuperMap.Web.iServerJava6R.FilterParameter();
		queryParam.name = queryLayerParams[i].name;
		queryParam.attributeFilter = queryLayerParams[i].where;
		queryParams.push(queryParam);

	}

	queryByGeometryParameters.queryParams = queryParams;
	queryByGeometryParameters.spatialQueryMode = SuperMap.Web.iServerJava6R.SpatialQueryMode.INTERSECT;
	queryByGeometryParameters.geometry = geo;

	// 执行几何查询
	var queryService = new SuperMap.Web.iServerJava6R.QueryByGeometryService(this.mapUrl);
	queryService.add_processCompleted(function(queryEventArgs) {
				var recordsets = queryEventArgs.result.recordsets;
				callback(recordsets);
			}.bind(this));
	queryService.processAsync(queryByGeometryParameters);
};

/**
 * 将绘制的图形加载到矢量要素图层上
 */
abbp.gis.supermap.Map.prototype.drawCompleted_ = function(drawGeometryArgs) {
	// var feature = new SuperMap.Web.Core.Feature();
	// feature.geometry = drawGeometryArgs.geometry;
	// this.featuresLayer.addFeature(feature);
	return drawGeometryArgs.geometry;
};

/**
 * 点查询
 * 
 * @param {QueryConfig}
 *            queryConfig 查询配置参数， 类型为QueryConfig查询配置参数对象
 * @param {function}
 *            onComplete 回调函数 onComplete(qusryResultSet)
 *            resultSet为QusryResultSet对象
 */
abbp.gis.supermap.Map.prototype.pointQuery = function() {
	var drawPoint = $create(SuperMap.Web.Actions.DrawPoint, {
				map : this.map
			}, null, null, null);
	this.map.set_action(drawPoint);
	drawPoint.add_actionCompleted(function(drawGeometryArgs) {
				var geo = this.drawCompleted_(drawGeometryArgs);
				this.geometryQuery(geo, this.queryConfig.queryLayerParams,
						this.queryResultDisplay);
			}.bind(this));
};

/**
 * 线查询
 * 
 * @param {QueryConfig}
 *            queryConfig 查询配置参数， 类型为QueryConfig查询配置参数对象
 * @param {function}
 *            onComplete 回调函数 onComplete(qusryResultSet)
 *            resultSet为QusryResultSet对象
 */
abbp.gis.supermap.Map.prototype.lineQuery = function() {
	var drawLine = $create(SuperMap.Web.Actions.DrawLine, {
				map : this.map
			}, null, null);
	this.map.set_action(drawLine);
	drawLine.add_actionCompleted(function(drawGeometryArgs) {
				var geo = this.drawCompleted_(drawGeometryArgs);
				this.geometryQuery(geo, this.queryConfig.queryLayerParams,
						this.queryResultDisplay);
			}.bind(this));
};

/**
 * 矩形查询
 * 
 * @param {QueryConfig}
 *            queryConfig 查询配置参数， 类型为QueryConfig查询配置参数对象
 * @param {function}
 *            onComplete 回调函数 onComplete(qusryResultSet)
 *            resultSet为QusryResultSet对象
 */
abbp.gis.supermap.Map.prototype.rectQuery = function() {
	var drawRectangle = $create(SuperMap.Web.Actions.DrawRectangle, {
				map : this.map
			}, null, null);
	this.map.set_action(drawRectangle);
	drawRectangle.add_actionCompleted(function(drawGeometryArgs) {
				var geo = this.drawCompleted_(drawGeometryArgs);
				this.geometryQuery(geo, this.queryConfig.queryLayerParams,
						this.queryResultDisplay);
			}.bind(this));
};

/**
 * 多边形查询
 * 
 * @param {QueryConfig}
 *            queryConfig 查询配置参数， 类型为QueryConfig查询配置参数对象
 * @param {function}
 *            onComplete 回调函数 onComplete(qusryResultSet)
 *            resultSet为QusryResultSet对象
 */
abbp.gis.supermap.Map.prototype.polygonQuery = function() {
	var drawPolygon = $create(SuperMap.Web.Actions.DrawPolygon, {
				map : this.map
			}, null, null);
	this.map.set_action(drawPolygon);
	drawPolygon.add_actionCompleted(function(drawGeometryArgs) {
				var geo = this.drawCompleted_(drawGeometryArgs);
				this.geometryQuery(geo, this.queryConfig.queryLayerParams,
						this.queryResultDisplay);
			}.bind(this));
};

/**
 * 测量距离
 * 
 * @param {function}
 *            onComplete 回调函数 onComplete(measureResult)
 *            measureResult为MeasureResult对象包括长度、单位
 */
abbp.gis.supermap.Map.prototype.measureDistance = function(onCompleted) {
	this.isMeasureDistance = true;
	var drawLineAction = $create(SuperMap.Web.Actions.DrawLine, {
				map : this.map
			}, null, null, null);
	drawLineAction.add_actionCompleted(function(drawGeometryArgs) {
				this.measureDrawCompleted(drawGeometryArgs, onCompleted);
			}.bind(this));
	this.map.set_action(drawLineAction);
};

/**
 * 测量面积
 * 
 * @param {function}
 *            onComplete 回调函数 onComplete(measureResult)
 *            measureResult为MeasureResult对象包括面积、单位
 */
abbp.gis.supermap.Map.prototype.measureArea = function(onCompleted) {
	this.isMeasureDistance = false;
	var drawPolygonAction = $create(SuperMap.Web.Actions.DrawPolygon, {
				map : this.map
			}, null, null, null);
	drawPolygonAction.add_actionCompleted(function(drawGeometryArgs) {
				this.measureDrawCompleted(drawGeometryArgs, onCompleted);
			}.bind(this));
	this.map.set_action(drawPolygonAction);
};

/**
 * 量算绘制回调函数
 */
abbp.gis.supermap.Map.prototype.measureDrawCompleted = function(
		drawGeometryArgs, onCompleted) {

	var feature = new SuperMap.Web.Core.Feature();
	feature.geometry = drawGeometryArgs.geometry;
	this.featuresLayer.addFeature(feature);

	var unit = new SuperMap.Web.Core.Units().meter;
	var measureParameters = new SuperMap.Web.iServerJava6R.MeasureParameters(
			drawGeometryArgs.geometry, unit);

	var measureService = new SuperMap.Web.iServerJava6R.MeasureService(this.mapUrl);

	// 默认为量算距离，如果量算面积，则需要将 measureMode 设置为 AREA
	if (!this.isMeasureDistance) {
		measureService
				.set_measureMode(SuperMap.Web.iServerJava6R.MeasureMode.AREA);
	}

	measureService.add_processCompleted(function(measureServiceArgs) {
				this.measureCompleted(measureServiceArgs, onCompleted)
			}.bind(this));
	measureService.processAsync(measureParameters);

};

/**
 * 量算结果回调函数
 */

abbp.gis.supermap.Map.prototype.measureCompleted = function(measureServiceArgs,
		onCompleted) {
	var distance = measureServiceArgs.get_result().get_distance();
	var area = measureServiceArgs.get_result().get_area();
	var unit = measureServiceArgs.get_result().get_unit();
	if (distance != -1) {
		onCompleted(distance + "米");
	} else {
		onCompleted(area + "平方米");
	}

}

/**
 * 地图上选择路径分析点位
 * 
 * @param callback
 *            回调函数 参数为路径分析点的坐标 结构为{'x':108.94,'y':32.23}
 */
abbp.gis.supermap.Map.prototype.selectNode = function(callback) {
	var drawPointAction = $create(SuperMap.Web.Actions.DrawPoint, {
				'map' : this.map
			}, null, null, null);
	drawPointAction.add_actionCompleted(function(drawArgs) {
				var img = document.createElement("img");
				img.src = abbp.baseJsPath + "lib/supermap/images/marker.gif";
				var marker = $create(SuperMap.Web.Core.Marker, {
							'id' : drawArgs.geometry.x + '_'
									+ drawArgs.geometry.y,
							'x' : drawArgs.geometry.x,
							'y' : drawArgs.geometry.y,
							'title' : "站点",
							'offsetX' : 8,
							'offsetY' : 8
						}, null, null, img);
				this.markerLayer.addMarker(marker);
				callback({
							'id' : marker.get_id(),
							'x' : marker.get_x(),
							'y' : marker.get_y()
						});
			}.bind(this));
	this.map.set_action(drawPointAction);
};

abbp.gis.supermap.Map.prototype.deleteMark = function(id) {
	this.markerLayer.removeMarkerById(id);
	this.markerLayer.refresh();
};

/**
 * 地图定位
 * 
 * @param {Geometry}
 *            geometry 定位图形，为Geometry类型对象
 */
abbp.gis.supermap.Map.prototype.locator = function(geometry) {
};

/**
 * 在地图上添加图形
 * 
 * @param {string}
 *            id 图形id
 * @param {Graphic}
 *            graphic图形，为Graphic类型对象
 */
abbp.gis.supermap.Map.prototype.addGraphic = function(id, graphic) {
};

/**
 * 删除地图上图形
 * 
 * @param {string}
 *            id 图形id
 */
abbp.gis.supermap.Map.prototype.removeGraphic = function(id) {
};

/**
 * 清除地图上所有图形
 */
abbp.gis.supermap.Map.prototype.clearGraphics = function() {
	this.featuresLayer.clearFeatures();
	this.clearMark_();
};

/**
 * 初始化鹰眼
 * 
 * @param container
 *            放置鹰眼的容器
 */
abbp.gis.supermap.Map.prototype.initOverviewMap = function(container) {
};

/**
 * 初始化图例
 * 
 * @param {LayerConfig[]}
 *            layerConfigs显示图例的图层配置数组
 * @param container
 *            放置图例的容器
 */
abbp.gis.supermap.Map.prototype.initiLegend = function(layerConfigs, container) {
};

/**
 * 绘制点
 * 
 * @param {function}
 *            onComplete 回调函数onComplete(geometry) geometry为绘制图形，为Geometry类型对象
 */
abbp.gis.supermap.Map.prototype.drawPoint = function() {
	var drawPoint = $create(SuperMap.Web.Actions.DrawPoint, {
				map : this.map
			}, null, null, null);
	this.map.set_action(drawPoint);
	drawPoint.add_actionCompleted(function(drawGeometryArgs) {
				this.drawCompleted_(drawGeometryArgs);
			}.bind(this));
};

/**
 * 绘制线
 * 
 * @param {function}
 *            onComplete 回调函数onComplete(geometry) geometry为绘制图形，为Geometry类型对象
 */
abbp.gis.supermap.Map.prototype.drawLine = function() {
	var drawLine = $create(SuperMap.Web.Actions.DrawLine, {
				map : this.map
			}, null, null);
	this.map.set_action(drawLine);
	drawLine.add_actionCompleted(function(drawGeometryArgs) {
				this.drawCompleted_(drawGeometryArgs);
			}.bind(this));
};

/**
 * 绘制矩形
 * 
 * @param {function}
 *            onComplete 回调函数onComplete(geometry) geometry为绘制图形，为Geometry类型对象
 */
abbp.gis.supermap.Map.prototype.drawRect = function() {
	var drawRect = $create(SuperMap.Web.Actions.DrawRectangle, {
				map : this.map
			}, null, null);
	this.map.set_action(drawRect);
	drawRect.add_actionCompleted(function(drawGeometryArgs) {
				this.drawCompleted_(drawGeometryArgs);
			}.bind(this));
};

/**
 * 绘制面
 * 
 * @param {function}
 *            onComplete 回调函数onComplete(geometry) geometry为绘制图形，为Geometry类型对象
 */
abbp.gis.supermap.Map.prototype.drawPolygon = function() {
	var drawPolygon = $create(SuperMap.Web.Actions.DrawPolygon, {
				map : this.map
			}, null, null);
	this.map.set_action(drawPolygon);
	drawPolygon.add_actionCompleted(function(drawGeometryArgs) {
				this.drawCompleted_(drawGeometryArgs);
			}.bind(this));
};
// ===========缓冲区分析==========================================
/**
 * 点状缓冲
 * 
 * @param distance
 *            缓冲距离，单位为米
 */
abbp.gis.supermap.Map.prototype.pointBuffer = function(distance) {
	var drawPoint = $create(SuperMap.Web.Actions.DrawPoint, {
				map : map.map
			}, null, null, null);
	map.map.set_action(drawPoint);
	drawPoint.add_actionCompleted(function(drawGeometryArgs) {
				var geo = map.drawCompleted_(drawGeometryArgs);
				abbp.gis.supermap.SpatialAnalyst.buffer(geo, distance, map,
						analystCompleted);
			});
};

/**
 * 线状缓冲
 * 
 * @param distance
 *            缓冲距离，单位为米
 */
abbp.gis.supermap.Map.prototype.lineBuffer = function(distance) {
	var drawLine = $create(SuperMap.Web.Actions.DrawLine, {
				map : map.map
			}, null, null, null);
	map.map.set_action(drawLine);
	drawLine.add_actionCompleted(function(drawGeometryArgs) {
				var geo = map.drawCompleted_(drawGeometryArgs);

				abbp.gis.supermap.SpatialAnalyst.buffer(geo, distance, map,
						analystCompleted);
			});
};

/**
 * 面状缓冲
 * 
 * @param distance
 *            缓冲距离，单位为米
 */
abbp.gis.supermap.Map.prototype.regionBuffer = function(distance) {
	var drawPolygon = $create(SuperMap.Web.Actions.DrawPolygon, {
				map : map.map
			}, null, null, null);
	map.map.set_action(drawPolygon);
	drawPolygon.add_actionCompleted(function(drawGeometryArgs) {
				var geo = map.drawCompleted_(drawGeometryArgs);
				abbp.gis.supermap.SpatialAnalyst.buffer(geo, distance, map,
						analystCompleted);
			});
};

/**
 * 鼠标勾绘地震事件
 */
abbp.gis.supermap.Map.prototype.mouseInputEq = function(callback) {
	var drawLine = $create(SuperMap.Web.Actions.DrawLine, {
				map : this.map
			}, null, null);
	this.map.set_action(drawLine);
	drawLine.add_actionCompleted(function(drawGeometryArgs) {
				var geo = this.drawCompleted_(drawGeometryArgs);
				var startPoint = geo.parts[0][0];
				var endPoint = geo.parts[0][1];
				var midX = (startPoint.x + endPoint.x) / 2;
				var midY = (startPoint.y + endPoint.y) / 2;
				var point = new SuperMap.Web.Core.Point2D(midX, midY);
				var geo = new SuperMap.Web.Core.GeoPoint(point);
				var eqParameter = {
					'direction' : {},
					'district' : '',
					'x' : 0,
					'y' : 0
				};
				eqParameter.x = midX.toFixed(2);
				eqParameter.y = midY.toFixed(2);
				eqParameter.direction = this.getAngle_(startPoint, endPoint);
				this.queryEqDistrict_(eqParameter, geo, callback)
			}.bind(this));
};

/**
 * 获取地震信息，包括默认破裂方向和地震所在行政区
 * 
 * @param x
 *            震中经度
 * @param y
 *            震中纬度
 * @param callback
 *            回调函数 参数为地震信息{'dierction' : 35.32,'district' : '陕西省西安市长安区'}
 */
abbp.gis.supermap.Map.prototype.getEqInfo = function(x, y, callback) {
	var point = new SuperMap.Web.Core.Point2D(x, y);
	var geo = new SuperMap.Web.Core.GeoPoint(point);

	this.queryNearest_(geo, 'Activefault@orcl_xian', this.getEqInfoCompleted_
					.bind(this), callback);

};

abbp.gis.supermap.Map.prototype.getEqInfoCompleted_ = function(queryResultArgs,
		geo, callback) {
	if (queryResultArgs.result.currentCount > 0) {

		var feature = queryResultArgs.result.recordsets[0].features[0];
		var geometry = feature.geometry;
		var startPoint = geometry.parts[0][0];
		var endPoint = geometry.parts[0][geometry.parts[0].length - 1];
		var eqParameter = {
			'direction' : {},
			'district' : ''
		};
		eqParameter.direction = this.getAngle_(startPoint, endPoint);
	}
	this.queryEqDistrict_(eqParameter, geo, callback);
};

/**
 * 查询震中所在的行政区
 * 
 * @param {}
 *            eqParameter
 * @param {}
 *            geo
 * @param {}
 *            callback
 */
abbp.gis.supermap.Map.prototype.queryEqDistrict_ = function(eqParameter, geo,
		callback) {
	var queryByGeometryParameters = new SuperMap.Web.iServerJava6R.QueryByGeometryParameters();
	var filterParameter = new SuperMap.Web.iServerJava6R.FilterParameter();
	filterParameter.name = 'County_Code@orcl_xian';
	queryByGeometryParameters.queryParams = [filterParameter];
	queryByGeometryParameters.spatialQueryMode = SuperMap.Web.iServerJava6R.SpatialQueryMode.INTERSECT;
	queryByGeometryParameters.geometry = geo;

	var queryService = new SuperMap.Web.iServerJava6R.QueryByGeometryService(this.mapUrl);
	queryService.add_processCompleted(function(queryEventArgs) {
				if (queryEventArgs.result.currentCount > 0) {
					var feature = queryEventArgs.result.recordsets[0].features[0];
					var record = abbp.gis.supermap.Record
							.fromSuperMapFeature(feature);
					eqParameter.district = record.getValue('FULL_NAME');
				}
				callback(eqParameter);
			});
	queryService.processAsync(queryByGeometryParameters);
};

/**
 * 根据两点获取此两点连成直线与水平线之间的夹角
 * 
 * @param startPoint
 *            起点
 * @param endPoint
 *            终点
 * @returns angle 角度
 */
abbp.gis.supermap.Map.prototype.getAngle_ = function(startPoint, endPoint) {
	var angle = 0;
	var direction = '';
	if (endPoint.x - startPoint.x == 0) {
		angle = 90;
		direction = '正北';
	} else {
		var k = (endPoint.y - startPoint.y) / (endPoint.x - startPoint.x);
		angle = Math.atan(k) * 180 / 3.14;
		if (k > 0) {
			direction = '北偏东' + (90 - angle).toFixed(2);
		} else {
			direction = '北偏西' + (90 + angle).toFixed(2);
			angle = 180 + angle;
		}
	}
	return {
		'caption' : direction,
		'value' : angle
	};
};

/**
 * 将资源配送路径添加到矢量图层
 * 
 * @param {abbp.gis.supermap.Geometry}
 *            geo 路径几何对象
 */
abbp.gis.supermap.Map.prototype.addPathLine = function(geo) {
	var feature = new SuperMap.Web.Core.Feature();
	var line = abbp.gis.supermap.Geometry.toSuperMapGeometry(geo);
	feature.geometry = line;
	this.featuresLayer.addFeature(feature);
};

abbp.gis.supermap.Map.prototype.queryResourceLayer = function(layerName,
		nameField, value, fields, callback) {
	var sqlQueryService = new SuperMap.Web.iServerJava6R.QueryBySQLService(this.mapUrl);
	var queryParamters = new SuperMap.Web.iServerJava6R.QueryBySQLParameters();
	var filterParameter = new SuperMap.Web.iServerJava6R.FilterParameter();
	filterParameter.name = layerName;
	if (value) {
		filterParameter.attributeFilter = nameField + ' like \'%' + value
				+ '%\'';
	}
	var filterFields = [];
	for (var i = 0, len = fields.length; i < len; i++) {
		filterFields.push(fields[i].fieldId);
	}
	// filterFields.push("SmID");
	filterParameter.fields = filterFields;

	queryParamters.queryParams = [filterParameter];
	queryParamters.expectCount = 100;

	sqlQueryService.add_processCompleted(function(queryEventArgs) {
				this.queryResourceLayerCompleted_(queryEventArgs, callback);
			}.bind(this));
	sqlQueryService.processAsync(queryParamters);
};

abbp.gis.supermap.Map.prototype.queryResourceLayerCompleted_ = function(
		queryEventArgs, callback) {
	var result = queryEventArgs.result;
	var dataGrid = '';
	if (result && result.currentCount) {
		var recordset = result.recordsets[0];
		var layerName = recordset.datasetName;
		var fields = recordset.fields;
		var captions = recordset.fieldCaptions;
		var columns = '<columns>';
		var rows = '<rows>'

		for (var i = 0, len = fields.length; i < len; i++) {
			if (fields[i].toLowerCase().indexOf('sm', 0) < 0) {
				columns += '<column name = "' + fields[i] + '" caption = "'
						+ captions[i] + '" visible="true"/>';
			}
			// else {
			// columns += '<column name = \"' + fields[i] + '\" caption = \"'
			// + captions[i] + '\" visible=\"false\"/>';
			// }
		}

		columns += '<column name = "X" caption = "X" visible="false"/>'
				+ '<column name = "Y" caption = "Y" visible="false"/>'
				+ '<column name = "code" caption = "图层名" visible = "false"/>';

		var features = recordset.features;
		for (var i = 0, len1 = features.length; i < len1; i++) {
			var feature = features[i];
			var rowValue = '';
			for (var j = 0, len2 = feature.attributes.fieldNames.length; j < len2; j++) {
				if (feature.attributes.fieldNames[j].toLowerCase().indexOf(
						'sm', 0) < 0) {
					rowValue += '<' + feature.attributes.fieldNames[j] + '>'
							+ feature.attributes.fieldValues[j] + '</'
							+ feature.attributes.fieldNames[j] + '>';
				}
			}

			var geo = feature.geometry;
			var x = (geo.bounds().leftBottom.x + geo.bounds().rightTop.x) / 2;
			var y = (geo.bounds().leftBottom.y + geo.bounds().rightTop.y) / 2;
			rowValue += '<X>' + x + '</X><Y>' + y + '</Y><code>' + layerName
					+ '</code>';

			rows += '<row>' + rowValue + '</row>';
		}

		dataGrid = '<?xml version="1.0" encoding="UTF-8"?><datagrid version="1.0"><grid><params></params>';
		dataGrid += columns + '</columns>' + rows + '</rows></grid></datagrid>';
	} else {
		dataGrid = '<?xml version="1.0" encoding="UTF-8"?><datagrid version="1.0"></datagrid>';
	}
	callback(dataGrid);
};

abbp.gis.supermap.Map.prototype.queryGeometryById = function(layerName, smId) {
	var sqlQueryService = new SuperMap.Web.iServerJava6R.QueryBySQLService(this.mapUrl);
	var queryParamters = new SuperMap.Web.iServerJava6R.QueryBySQLParameters();
	var filterParameter = new SuperMap.Web.iServerJava6R.FilterParameter();
	filterParameter.name = layerName;
	filterParameter.attributeFilter = 'SmID = ' + smId;
	queryParamters.queryParams = [filterParameter];

	sqlQueryService.add_processCompleted(this.locateGeometry_.bind(this));
	sqlQueryService.processAsync(queryParamters);
};

abbp.gis.supermap.Map.prototype.locateGeometry_ = function(queryEventArgs) {
	var result = queryEventArgs.result;
	if (result && result.currentCount > 0) {
		var recordset = result.recordsets[0];
		var feature = recordset.features[0];
		var geo = feature.geometry;
		if (feature.geometry instanceof SuperMap.Web.Core.GeoPoint) {
			var img = document.createElement("img");
			img.src = abbp.baseJsPath + "lib/supermap/images/marker.gif";
			var marker = $create(SuperMap.Web.Core.Marker, {
						'id' : geo.x + '_' + geo.y,
						'x' : geo.x,
						'y' : geo.y,
						'offsetX' : 8,
						'offsetY' : 8
					}, null, null, img);
			this.clearGraphics();
			this.markerLayer.addMarker(marker);

			var center = new SuperMap.Web.Core.Point2D(geo.x, geo.y);
			this.map.zoomToScale(0.0001, center);
		} else {
			var style = new SuperMap.Web.Core.Style();
			style.opacity = 0.5;
			style.strokeColor = 'Red';
			feature.style = style;
			this.clearGraphics();
			this.featuresLayer.addFeature(feature);
			this.map.set_viewBounds(geo.bounds());
		}

	}
};

abbp.gis.supermap.Map.prototype.clearMark_ = function() {
	var markers = this.markerLayer.get_markers();
	if (markers) {
		// for (var marker in markers) {
		// if (markers.hasOwnProperty(marker)) {
		// if (markers[marker].get_id() != 'eqCenter') {
		// this.markerLayer.removeMarker(markers[marker]);
		// }
		// }
		// }
		for (var i = markers.length - 1; i >= 0; i--) {
			if (markers[i].get_id() != 'eqCenter'
					|| markers[i].get_id() != 'eqCenterText') {
				this.markerLayer.removeMarker(markers[i]);
			}
		}
	}
};

/**
 * 添加震中gif图标
 * 
 * @param Number
 *            x 震中经度
 * @param Number
 *            y 震中纬度
 */
abbp.gis.supermap.Map.prototype.addEqCenterMark = function(eqInfo) {
	var x = eqInfo.longitude;
	var y = eqInfo.latitude;
	var location = eqInfo.location;
	var m = eqInfo.m;
	var label = location + '发生' + m + '级地震';

	var img = document.createElement("img");
	img.src = abbp.baseJsPath + "lib/supermap/images/eq_marker_red.gif";
	var marker = $create(SuperMap.Web.Core.Marker, {
				'id' : 'eqCenter',
				'x' : x,
				'y' : y,
				'offsetX' : 0,
				'offsetY' : 0
			}, null, null, img);
	var txt = document.createElement("div");
	txt.style.cssText = 'color:#F00;font-weight:bold';
	txt.innerHTML = label;
	var txtMark = $create(SuperMap.Web.Core.Marker, {
				'id' : 'eqCenterText',
				'x' : x,
				'y' : y,
				'offsetY' : 20
			}, null, null, txt);
	if (this.markerLayer) {
		this.markerLayer.removeMarkerById('eqCenter');
		this.markerLayer.removeMarkerById('eqCenterText');
		this.markerLayer.addMarker(marker);
		this.markerLayer.addMarker(txtMark);
	}

};

abbp.gis.supermap.Map.prototype.aftershockIncidence = function(eventId) {
	var eventId = {
		'eventId' : eventId + ''
	};
	abbp.ajax.servlet.execAsynCmd('AftershockIncidenceCmd', eventId,
			this.aftershockIncidenceCompleted_.bind(this));
};

abbp.gis.supermap.Map.prototype.aftershockIncidenceCompleted_ = function(req) {
	var result = req.responseText;
	var resultJson = eval('(' + result + ')');
	if (resultJson.success) {
		var geoRegion = resultJson.info;
		var smRegion = abbp.gis.supermap.Geometry.toSuperMapGeometry(geoRegion);
		abbp.gis.supermap.SpatialAnalyst.buffer(smRegion, 5000, this, abbp.fGo);
	} else {
		alert(resultJson.info);
	}
};

abbp.gis.supermap.Map.prototype.showSpread = function(result) {
	var json = eval('(' + result + ')');
	if (json.success) {
		this.clearGraphics();
		for (var i = 0, len = json.info.length; i < len; i++) {
			var smRegion = abbp.gis.supermap.Geometry
					.toSuperMapGeometry(json.info[i]);
			var feature = new SuperMap.Web.Core.Feature();
			var style = new SuperMap.Web.Core.Style();
			style.stroke = true;
			style.strokeColor = "#55ff44";
			style.fill = true;
			style.fillColor = "#C01800";
			style.opacity = 0.5;
			style.lineWidth = 1;
			feature.style = style;
			feature.geometry = smRegion;
			this.featuresLayer.addFeature(feature);
		}
		var center = new SuperMap.Web.Core.Point2D(108.842130, 34.229124);
		var scale = 0.000003;
		this.map.zoomToScale(scale, center);
		this.featuresLayer.refresh();
	} else {
		alert(json.info);
	}
}

abbp.gis.supermap.Map.prototype.setBarrierEdge = function(callback) {
	var drawPoint = $create(SuperMap.Web.Actions.DrawPoint, {
				map : this.map
			}, null, null, null);
	this.map.set_action(drawPoint);
	drawPoint.add_actionCompleted(function(drawGeometryArgs) {
				var geo = this.drawCompleted_(drawGeometryArgs);

				this.queryNearest_(geo, 'RoadNet_Node@orcl_xian',
						this.setBarrierEdgeCompleted_.bind(this), callback);

				var img = document.createElement("img");
				img.src = abbp.baseJsPath
						+ "lib/supermap/images/marker_red.gif";
				var marker = $create(SuperMap.Web.Core.Marker, {
							'id' : geo.x + '_' + geo.y,
							'x' : geo.x,
							'y' : geo.y,
							'title' : "障碍点",
							'offsetX' : 8,
							'offsetY' : 8
						}, null, null, img);
				this.markerLayer.addMarker(marker);

			}.bind(this));
};

abbp.gis.supermap.Map.prototype.setBarrierEdgeCompleted_ = function(
		queryResultArgs, geo, callback) {
	if (queryResultArgs.result.currentCount > 0) {
		var feature = queryResultArgs.result.recordsets[0].features[0];
		var record = abbp.gis.supermap.Record.fromSuperMapFeature(feature);
		var barrierEdgeId = record.getValue('SmID');
		callback({
					'id' : geo.x + '_' + geo.y,
					'barrierEdgeId' : barrierEdgeId
				});
	}
};

abbp.gis.supermap.Map.prototype.queryNearest_ = function(geo, layerName,
		onCompleted, callback) {
	var queryByDistanceService = new SuperMap.Web.iServerJava6R.QueryByDistanceService(this.mapUrl);

	var queryByDistanceParams = new SuperMap.Web.iServerJava6R.QueryByDistanceParameters();
	queryByDistanceParams.geometry = geo;
	queryByDistanceParams.expectCount = 1;
	queryByDistanceParams.distance = 100000;
	queryByDistanceParams.isNearest = true;
	var filterParameter = new SuperMap.Web.iServerJava6R.FilterParameter();
	filterParameter.name = layerName;
	queryByDistanceParams.queryParams = [filterParameter];

	queryByDistanceService.add_processCompleted(function(queryResultArgs) {
				onCompleted(queryResultArgs, geo, callback);
			});
	queryByDistanceService.processAsync(queryByDistanceParams);
};

abbp.gis.supermap.Map.prototype.createTheme = function(eventid, code) {
	var url = String.format('{0}gis/theme/{1}/{2}', REST_SERVICES_ADDRESS,
			eventid, code);
	abbp.ajax.servlet.doGet(url, function(req) {
		var json = JSON.parse(req.responseText);
		var layerConfig = eval('(' + json['result']['value'] + ')');
		var themeLayers = layerConfig.map.layers;
		var templateMap = layerConfig.map.templateMap;
		var tempSublayers = [];
		if (templateMap['@name']) {
			var templateLayers = templateMap.layers.templateLayer;
			for (var i = 0, len = templateLayers.length; i < len; i++) {
				var layerName = this.layersInfo[templateLayers[i].layerKey].name;
				var tempSublayer = this.templateSublayers[layerName];
				if (tempSublayer.name == '地震影响场标注'
						|| tempSublayer.name == '地震烈度分布'
						|| tempSublayer.name == 'eqPoint@orcl_xian'
						|| tempSublayer.name == '当前地震位置标注') {
					tempSublayer.displayFilter = 'eventid = ' + eventid;
				}
				tempSublayers.push({
							'name' : layerName,
							'subLayer' : tempSublayer
						});
			}
		}

		var postData = '[{"type": "UGC","subLayers": {"layers": [';
		var themeParameters = new SuperMap.Web.iServerJava6R.ThemeParameters();
		if (themeLayers['rangeLayer'] || themeLayers['uniqueLayer']
				|| themeLayers['graphLayer']) {
			for (themeLayer in themeLayers) {
				if (themeLayers.hasOwnProperty(themeLayer)) {
					var layer = themeLayers[themeLayer];
					var themes = [];
					switch (layer.type) {
						case 'UNIQUE' :
							var uniqueLayer = new SuperMap.Web.iServerJava6R.ThemeUnique();
							uniqueLayer.uniqueExpression = layer.expresion;
							var items = [];
							var uniqueItems = layer.items.uniqueItem;
							for (var i = 0, len = uniqueItems.length; i < len; i++) {
								var uniqueItem = new SuperMap.Web.iServerJava6R.ThemeUniqueItem();
								uniqueItem.caption = uniqueItems[i].caption;
								uniqueItem.unique = uniqueItems[i].value;
								var style = abbp.gis.supermap.Style
										.fromJson(uniqueItems[i].style);
								uniqueItem.style = style;
								items.push(uniqueItem);
							}
							uniqueLayer.items = items;
							themes.push(uniqueLayer);
							break;
						case 'RANGE' :
							var rangeUrl = String.format(
									'{0}gis/theme/range/{1}/{2}',
									REST_SERVICES_ADDRESS, layer.joinData,
									layer.expresion);
							abbp.ajax.servlet.doGet(rangeUrl, function(req) {
										this.getRangeComplete_(req, layer,
												tempSublayers)
									}.bind(this), null, null, {
										'accept' : 'application/json'
									});
							break;
						case 'GRAPH' :
							var graphLayer = new SuperMap.Web.iServerJava6R.ThemeGraph();
							graphLayer.barWidth = layer.barWidth;
							graphLayer.graphType = layer.graphType;
							var graphSize = new SuperMap.Web.iServerJava6R.ThemeGraphSize();
							graphSize.maxGraphSize = layer.maxGraphSize;
							graphSize.minGraphSize = layer.miniGraphSize;
							graphLayer.graphSize = graphSize;
							var items = [];
							var graphItems = layer.items.graphItem;
							for (var i = 0, len = graphItems.length; i < len; i++) {
								var graphItem = new SuperMap.Web.iServerJava6R.ThemeGraphItem();
								graphItem.caption = graphItems[i].caption;
								graphItem.graphExpression = graphItems[i].graphExpresstion;
								var style = abbp.gis.supermap.Style
										.fromJson(graphItems[i].style);
								graphItem.uniformStyle = style;
								items.push(graphItem);
							}
							graphLayer.items = items;
							themes.push(graphLayer);
							break;
					}
					if (layer.type != 'RANGE') {
						themeParameters.datasetName = layer.joinData;// this.layersInfo[layer.layerKey].dataset;
						themeParameters.dataSourceName = 'orcl_xian';// this.layersInfo[layer.layerKey].datasource;
						// if (layer.joinType == 'EXTERNAL') {
						// var joinItem = new
						// SuperMap.Web.iServerJava6R.JoinItem();
						// joinItem.foreignTableName = layer.joinData;
						// joinItem.joinFilter = String.format(
						// '{0}.{1} = {2}.{3}',
						// this.layersInfo[layer.layerKey].dataset,
						// layer.layerField, layer.joinData,
						// layer.joinField);
						// joinItem.joinType = 'LEFTJOIN';
						// themeParameters.joinItems = [joinItem];
						// }
						themeParameters.themes = themes;

						var themeJson = this.getThemeLayerParameter_(
								themeParameters, layer.caption)
						if (layer.type == 'UNIQUE') {
							for (var i = 0, len = tempSublayers.length; i < len; i++) {
								if (tempSublayers[i].name == (this.layersInfo[layer.layerKey].dataset
										+ '@' + this.layersInfo[layer.layerKey].datasource)) {
									var themeObj = eval('(' + themeJson + ')');
									tempSublayers[i] = {
										'name' : '专题图',
										'subLayer' : themeObj
									};
								}
							}
						} else {
							postData += themeJson + ','
						}

						for (var i = 0, len = tempSublayers.length; i < len; i++) {
							postData += SuperMap.Web.Utility
									.toJSON(tempSublayers[i]['subLayer'])
									+ ',';
						}

						postData += ']},"name": "xian2"}]';
						var themeService = new SuperMap.Web.iServerJava6R.ThemeService(SuperMapConfig.TEMPLATE_MAP_URL);
						themeService.add_processCompleted(function(themeArgs) {
									this.addThemeComplete_(themeArgs,
											themeLayers)
								}.bind(this));
						themeService.processAsync(postData);
					}
				}
			}
		} else {
			for (var i = 0, len = tempSublayers.length; i < len; i++) {
				postData += SuperMap.Web.Utility
						.toJSON(tempSublayers[i]['subLayer'])
						+ ',';
			}
			postData += ']},"name": "xian2"}]';
			var themeService = new SuperMap.Web.iServerJava6R.ThemeService(SuperMapConfig.TEMPLATE_MAP_URL);
			themeService.add_processCompleted(function(themeArgs) {
						this.addThemeComplete_(themeArgs, themeLayers)
					}.bind(this));
			themeService.processAsync(postData);
		}
	}.bind(this), null, null, {
		'accept' : 'application/json'
	});
};

abbp.gis.supermap.Map.prototype.getRangeComplete_ = function(req, layer,
		tempSublayers) {
	var json = JSON.parse(req.responseText);
	var range = eval('(' + json['result']['value'] + ')');

	var themeParameters = new SuperMap.Web.iServerJava6R.ThemeParameters();
	var themes = [];

	var rangeLayer = new SuperMap.Web.iServerJava6R.ThemeRange();
	var rangeItems = layer.items.rangeItem;
	rangeLayer.rangeExpression = layer.expresion;
	rangeLayer.rangeMode = 'EQUALINTERVAL';
	rangeLayer.rangeParameter = rangeItems.length;
	var items = [];
	var min = range.min;
	var interval = (range.max - range.min) / rangeItems.length;
	for (var i = 0, len = rangeItems.length; i < len; i++) {
		var rangeItem = new SuperMap.Web.iServerJava6R.ThemeRangeItem();
		rangeItem.start = min + interval * i;
		rangeItem.end = min + interval * (i + 1);
		rangeItem.caption = rangeItem.start.toFixed(2) + '~'
				+ rangeItem.end.toFixed(2);
		var style = abbp.gis.supermap.Style.fromJson(rangeItems[i].style);
		rangeItem.style = style;
		items.push(rangeItem);
	}
	rangeLayer.items = items;
	themes.push(rangeLayer);

	themeParameters.datasetName = layer.joinData;// this.layersInfo[layer.layerKey].dataset;
	themeParameters.dataSourceName = 'orcl_xian';// this.layersInfo[layer.layerKey].datasource;
	// if (layer.joinType == 'EXTERNAL') {
	// var joinItem = new
	// SuperMap.Web.iServerJava6R.JoinItem();
	// joinItem.foreignTableName = layer.joinData;
	// joinItem.joinFilter = String.format(
	// '{0}.{1} = {2}.{3}',
	// this.layersInfo[layer.layerKey].dataset,
	// layer.layerField, layer.joinData,
	// layer.joinField);
	// joinItem.joinType = 'LEFTJOIN';
	// themeParameters.joinItems = [joinItem];
	// }
	themeParameters.themes = themes;

	var themeJson = this
			.getThemeLayerParameter_(themeParameters, layer.caption)

	for (var i = 0, len = tempSublayers.length; i < len; i++) {
		if (tempSublayers[i].name == (this.layersInfo[layer.layerKey].dataset
				+ '@' + this.layersInfo[layer.layerKey].datasource)) {
			var themeObj = eval('(' + themeJson + ')');
			tempSublayers[i] = {
				'name' : '专题图',
				'subLayer' : themeObj
			};
		}
	}

	var postData = '[{"type": "UGC","subLayers": {"layers": [';
	for (var i = 0, len = tempSublayers.length; i < len; i++) {
		postData += SuperMap.Web.Utility.toJSON(tempSublayers[i]['subLayer'])
				+ ',';
	}
	postData += ']},"name": "xian2"}]';

	var themeService = new SuperMap.Web.iServerJava6R.ThemeService(SuperMapConfig.TEMPLATE_MAP_URL);
	themeService.add_processCompleted(function(themeArgs) {
				this.addThemeComplete_(themeArgs, [layer])
			}.bind(this));
	themeService.processAsync(postData);
};

abbp.gis.supermap.Map.prototype.getThemeLayerParameter_ = function(
		themeParameters, caption) {
	var g = "";
	for (var theme in themeParameters.themes) {
		if (themeParameters.themes.hasOwnProperty(theme)) {
			if (themeParameters.themes[theme] instanceof SuperMap.Web.iServerJava6R.ThemeRange) {
				var a = themeParameters.themes[theme];
				var f = "RANGE"
			} else {
				if (themeParameters.themes[theme] instanceof SuperMap.Web.iServerJava6R.ThemeUnique) {
					var a = themeParameters.themes[theme];
					var f = "UNIQUE"
				} else {
					if (themeParameters.themes[theme] instanceof SuperMap.Web.iServerJava6R.ThemeLabel) {
						var a = new Object();
						SuperMap.Web.iServerJava6R.ThemeLabel._toObject(
								themeParameters.themes[theme], a);
						var f = "LABEL"
					} else {
						if (themeParameters.themes[theme] instanceof SuperMap.Web.iServerJava6R.ThemeGraph) {
							var a = new Object();
							SuperMap.Web.iServerJava6R.ThemeGraph._toObject(
									themeParameters.themes[theme], a);
							var f = "GRAPH"
						} else {
							if (themeParameters.themes[theme] instanceof SuperMap.Web.iServerJava6R.ThemeGraduatedSymbol) {
								var a = new Object();
								SuperMap.Web.iServerJava6R.ThemeGraduatedSymbol
										._toObject(
												themeParameters.themes[theme],
												a);
								var f = "GRADUATEDSYMBOL"
							} else {
								if (themeParameters.themes[theme] instanceof SuperMap.Web.iServerJava6R.ThemeDotDensity) {
									var a = new Object();
									SuperMap.Web.iServerJava6R.ThemeDotDensity
											._toObject(
													themeParameters.themes[theme],
													a);
									var f = "DOTDENSITY"
								}
							}
						}
					}
				}
			}
			var e = SuperMap.Web.Utility.toJSON(a);
			e = e.slice(0, -1);
			e += ',"memoryData": null,';
			e += '"type": "' + f + '"},';
			g += '{"theme": ' + e + '"caption":"' + caption
					+ '","type": "UGC","ugcLayerType": "THEME",';
			if (themeParameters.joinItems
					&& themeParameters.joinItems.length > 0) {
				g += '"joinItems":'
						+ SuperMap.Web.Utility
								.toJSON(themeParameters.joinItems) + ","
			}
			g += '"datasetInfo": {"name": "' + themeParameters.datasetName
					+ '","dataSourceName": "' + themeParameters.dataSourceName
					+ '"}}'
		}
	}
	return g
};

abbp.gis.supermap.Map.prototype.addThemeComplete_ = function(themeEventArgs,
		themeLayers) {
	if (themeEventArgs.result.resourceInfo.succeed) {
		this.map.removeLayer();
		var themeLayer = $create(SuperMap.Web.Mapping.TiledDynamicRESTLayer, {
					url : SuperMapConfig.TEMPLATE_MAP_URL
				}, null, null, null);
		var layerID = themeEventArgs.result.resourceInfo.id;
		themeLayer.set_layersID(layerID);
		themeLayer.set_enableServerCaching(false);
		// 将专题图背景透明，以此可以显示底图
		themeLayer.set_transparent(true);

		this.map.addLayer(themeLayer);
		this.map.set_viewBounds(this.mapBounds);

		var tempLayersetUrl = SuperMapConfig.TEMPLATE_MAP_URL
				+ "/tempLayersSet/" + layerID + ".jsonp";
		SuperMap.Web.Service.Committer.REST(tempLayersetUrl, "GET", null, null,
				null, function(req) {
					this.getThemeLegend_(req[0], themeLayers, layerID);
				}.bind(this), null, null)
	}

};

abbp.gis.supermap.Map.prototype.getThemeLegend_ = function(themeLayerset,
		themeLayers, layerID) {
	var subLayers = themeLayerset.subLayers.layers;
	var legends = [];
	for (i in themeLayers) {
		if (themeLayers.hasOwnProperty(i)) {
			var themeCaption = themeLayers[i].caption;
			var themeName = '';
			var itmes = [];
			for (var j = 0, len1 = subLayers.length; j < len1; j++) {
				if (subLayers[j].caption == themeCaption) {
					themeName = subLayers[j].name;
					items = subLayers[j].theme.items;
					break;
				}
			}
			if (themeName) {
				themeName = themeName.replace(/#/g, ".");
				var imageUrl = SuperMapConfig.TEMPLATE_MAP_URL
						+ '/tempLayersSet/' + layerID + '/' + themeName
						+ '@@xian2/legend.png?width=16&height=16';
				var legend = "{'caption':'" + themeCaption + "','imgUrl':'"
						+ imageUrl + "','items':[";

				for (var k = 0, len = items.length; k < len; k++) {
					var itemCaption = items[k].caption;
					var itemImgUrl = SuperMapConfig.TEMPLATE_MAP_URL
							+ '/tempLayersSet/' + layerID + '/' + themeName
							+ '@@xian2/items/' + k
							+ '/legend.png?width=16&height=16';
					legend += "{'caption':'" + itemCaption + "','imgUrl':'"
							+ itemImgUrl + "'},";
				}
				legend += ']}';

				var legendObj = eval('(' + legend + ')');
				legends.push(legendObj);
			}
		}
	}
	return legends;
};

/**
 * 手动绘制烈度圈
 */
abbp.gis.supermap.Map.prototype.drawInty = function(eventId) {
	var editurl = String.format('{0}gis/inty/edit/{1}', REST_SERVICES_ADDRESS,
			eventId)
	abbp.ajax.servlet.doGet(editurl, function(req) {
				var result = JSON.parse(req.responseText)['result'];
				if (result.rtnCode == 0) {
					this.addEditIntyLayer();
				}
			}.bind(this), null, null, {
				'accept' : 'application/json'
			});
};

abbp.gis.supermap.Map.prototype.addEditIntyLayer = function() {
	// 初始化图层
	this.layer = $create(SuperMap.Web.Mapping.TiledDynamicRESTLayer, {
				url : SuperMapConfig.INTY_URL,
				enableServerCaching : false,
				transparent : true
			}, {
				initialized : this.editIntyLayerInitialized_.bind(this)
			}, null, null);
};

abbp.gis.supermap.Map.prototype.editIntyLayerInitialized_ = function(layer) {
	this.map.addLayer(layer);
};

abbp.gis.supermap.Map.prototype.addInty = function() {
	var drawPolygon = $create(SuperMap.Web.Actions.DrawPolygon, {
				map : this.map
			}, null, null, null);
	this.map.set_action(drawPolygon);
	drawPolygon.add_actionCompleted(this.addIntyCompleted_.bind(this));
};

abbp.gis.supermap.Map.prototype.addIntyCompleted_ = function(drawGeometryArgs) {
	var feature = new SuperMap.Web.Core.Feature();
	feature.geometry = drawGeometryArgs.geometry;
	feature.attributes.fieldNames = ['EVENTID', 'INTY', 'INTYLABEL'];
	feature.attributes.fieldValues = [80, 8, 'VIII'];

	this.featuresLayer.addFeature(feature);

	var parameter = new SuperMap.Web.iServerJava6R.Data.EditFeaturesParameters();
	parameter.features = [feature];
	parameter.editType = SuperMap.Web.iServerJava6R.Data.EditType.ADD;

	var editFeaturesService = new SuperMap.Web.iServerJava6R.Data.EditFeaturesService(SuperMapConfig.EDIT_FEATURES_URL);
	editFeaturesService.add_processCompleted(function(editFeaturesEventArgs) {
				if (editFeaturesEventArgs.result.succeed) {
					this.featuresLayer.clearFeatures();
					this.map.refresh();
					alert("添加烈度圈成功！");
				} else {
					alert("添加烈度圈失败！");
				}
			}.bind(this));
	editFeaturesService.processAsync(parameter);
};

abbp.gis.supermap.Map.prototype.delInty = function() {
	var drawPoint = $create(SuperMap.Web.Actions.DrawPoint, {
				map : this.map
			}, null, null, null);
	this.map.set_action(drawPoint);
	drawPoint.add_actionCompleted(this.delIntyCompleted_.bind(this));
};

abbp.gis.supermap.Map.prototype.delIntyCompleted_ = function(drawGeometryArgs) {
	var queryParam = new SuperMap.Web.iServerJava6R.Data.GetFeaturesByGeometryParameters();
	queryParam.spatialQueryMode = SuperMap.Web.iServerJava6R.SpatialQueryMode.INTERSECT;
	queryParam.datasetNames = ["orcl_xian:Edit_LD"];
	queryParam.geometry = drawGeometryArgs.geometry;

	var queryService = new SuperMap.Web.iServerJava6R.Data.GetFeaturesByGeometryService(SuperMapConfig.DATA_URL);
	queryService.add_processCompleted(this.onQueryDeleteComplete_.bind(this));
	queryService.processAsync(queryParam);

};

abbp.gis.supermap.Map.prototype.onQueryDeleteComplete_ = function(
		getFeaturesEventArgs) {
	var result = getFeaturesEventArgs.result;
	deleteIDs = new Array();

	if (result && result.features) {
		for (var i = 0; i < result.features.length; i++) {
			// 显示要删除地物，并记录要删除地物的 id 号
			this.featuresLayer.addFeature(result.features[i]);
			deleteIDs.push(result.features[i].attributes.fieldValues[0]);
		}
	}

	var parameter = new SuperMap.Web.iServerJava6R.Data.EditFeaturesParameters();
	parameter.IDs = deleteIDs;
	parameter.editType = SuperMap.Web.iServerJava6R.Data.EditType.DELETE;

	// 与服务器交互
	var editFeaturesService = new SuperMap.Web.iServerJava6R.Data.EditFeaturesService(SuperMapConfig.EDIT_FEATURES_URL);
	editFeaturesService.add_processCompleted(function(editFeaturesEventArgs) {
				if (editFeaturesEventArgs.result.succeed) {
					this.featuresLayer.clearFeatures();
					this.map.refresh();
					alert("删除烈度圈成功！");
				} else {
					alert("删除烈度圈失败！");
				}
			}.bind(this));
	editFeaturesService.processAsync(parameter);

};

abbp.gis.supermap.Map.prototype.editInty = function() {
	var drawPoint = $create(SuperMap.Web.Actions.DrawPoint, {
				map : this.map
			}, null, null, null);
	this.map.set_action(drawPoint);
	drawPoint.add_actionCompleted(this.editQuery_.bind(this));

};

abbp.gis.supermap.Map.prototype.editQuery_ = function(drawGeometryArgs) {
	var queryParam = new SuperMap.Web.iServerJava6R.FilterParameter();
	queryParam.name = "Edit_LD@orcl_xian";
	var queryParams = [queryParam];
	var queryByGeometryParameters = new SuperMap.Web.iServerJava6R.QueryByGeometryParameters();
	queryByGeometryParameters.queryParams = queryParams;
	queryByGeometryParameters.spatialQueryMode = SuperMap.Web.iServerJava6R.SpatialQueryMode.INTERSECT;
	queryByGeometryParameters.geometry = drawGeometryArgs.geometry;

	var queryService = new SuperMap.Web.iServerJava6R.QueryByGeometryService(SuperMapConfig.INTY_URL);
	queryService.add_processCompleted(this.onEditQueryComplete_.bind(this));
	queryService.processAsync(queryByGeometryParameters);
};

abbp.gis.supermap.Map.prototype.onEditQueryComplete_ = function(queryEventArgs) {
	if (this.featuresLayer.get_features() != null) {
		this.featuresLayer.clearFeatures();
	}
	var result = queryEventArgs.result;

	if (result && result.recordsets) {
		for (var i = 0; i < result.recordsets.length; i++) {
			if (result.recordsets[i].features) {
				for (var j = 0; j < result.recordsets[i].features.length; j++) {
					var queriedFeature = new SuperMap.Web.Core.Feature();
					queriedFeature = result.recordsets[i].features[j];
					this.featuresLayer.addFeature(queriedFeature);
				}
			}
		}
	}

	var editAction = $create(SuperMap.Web.Actions.EditFeature, {
				map : this.map,
				featuresLayer : this.featuresLayer
			}, null, null, null);
	this.map.set_action(editAction);
	editAction.add_actionCompleted(this.editIntyCompleted_.bind(this));

};

abbp.gis.supermap.Map.prototype.editIntyCompleted_ = function(
		editFeatureEventArgs) {
	var feature = editFeatureEventArgs.feature;

	var parameter = new SuperMap.Web.iServerJava6R.Data.EditFeaturesParameters();
	parameter.features = [feature];
	parameter.editType = SuperMap.Web.iServerJava6R.Data.EditType.UPDATE;

	var editFeaturesService = new SuperMap.Web.iServerJava6R.Data.EditFeaturesService(SuperMapConfig.EDIT_FEATURES_URL);
	editFeaturesService.add_processCompleted(function(editFeaturesEventArgs) {
				if (editFeaturesEventArgs.result.succeed) {
					this.featuresLayer.clearFeatures();
					this.map.refresh();
					alert("编辑烈度圈成功！");
				} else {
					alert("编辑烈度圈失败！");
				}
			}.bind(this));
	editFeaturesService.processAsync(parameter);

};

abbp.gis.supermap.Map.prototype.createStationInty = function() {
	var url = String.format('{0}gis/inty/create', REST_SERVICES_ADDRESS)
	abbp.ajax.servlet.doGet(url, function(req) {
				var result = JSON.parse(req.responseText)['result'];
				if (result.rtnCode == 0) {
					this.reload('StationLD');
					this.clearGraphics();
				} else {
					alert('未能生成测站烈度圈！');
				}
			}.bind(this), null, null, {
				'accept' : 'application/json'
			});
};